import { createAsyncThunk } from '@reduxjs/toolkit';
import axios, { AxiosError } from 'axios';
import { API } from '../../helpers/API';
import { RootState } from '..';

export interface IBall {
  id: number;
  name: string;
  image: string;
  price: number;
  count: number;
  title: string;
  description: string;
  favorite?: boolean;
}

export interface IResponse {
        id: number,
        name: string,
        image: string,
        price: number,
        count: number,
        title: string,
        description: string,
        favorite: false,
        user: {
            email: string,
            fullName: string,
            id: number
        }
    }
export const fetchUserMeSlice = createAsyncThunk<IResponse, IBall, {state: RootState}>(
	'cart/fetchCartPostSlice',
	async (dataFromCart, thunkAPI) => {
		try {
			const token = thunkAPI.getState().authorization.user.token;
			const { data } = await axios.get(`${API}/auth_me`, {
				headers: { 
					Authorization: `Bearer ${token}`	
				}
			});
			return data;
		} catch (error) {
			if (error instanceof AxiosError) {
				throw new Error(error.response?.data.message);
			}
		}
	}
);